<?php
class Parameter{
	//ver=10171
	
	//addOption(string $key, string/array $value)

	//SimpleXMLElement object
	private $_xml; 
	//Configuaration file path
	private $_file;
	
	//Parameters
	public $title;
	public $shell;
	public $span;
	public $csv;
	public $tip;
	
	//__counstruct(string $file)
	
	//Constructor.
	public function __construct($file){
		try{
			$xml=new SimpleXMLElement($file,NULL,TRUE);
		}
		catch(Exception $e){
			echo 'Failed to load configuration file:'.$e->getMessage();
		}
		$this->_xml=$xml;
		$this->_file=$file;
		
		$this->title=self::get('title');
		$this->shell=self::get('shell');
		$this->csv=self::get('csv');
		$this->tip=self::get('tip');		
		$this->span=self::get('span');		
		// $obj=$xml->span;
		// $this->span=self::_toArray($obj,true);
	}
	private function _save(){
		$this->_xml->asXML($this->_file);
	}
	
	//works with other functions.
	private function _getObject($string){	
		eval("\$obj=\$this->_xml->$string;");
		return $obj;
	}
	
	//void addOption(string $mod,string $key,string/number $value)
	public function addOption($key,$value){
		if(is_array($value)&&!empty($value)){
			foreach($value as $it)
				self::addOption($mod,$key,$it);
		}
		else{
			$obj=self::_getObject($key);
			$obj->addChild('option',$value);
		}
		self::_save();
		$this->$key=self::get($key);
	}
	
	//$index begins with 1.
	public function updateOption($key,$index,$value){
		if(!is_array($value)&&!empty($value)){
			$obj=self::_getObject($key);
			$obj->option[$index-1]=$value;
			self::_save();
			$this->$key=self::get($key);
		}	
	}
	
	//Add a new span to SPAN section.
	public function addSpan($key,$value){
		if(!is_array($value)&&!empty($value)){
			$obj=self::_getObject('span');
			$obj->addChild($key,$value);
			self::_save();
			$this->span=self::get('span');
		}		
	}
	
	//$index begins with 1.
	public function updateSpan($key,$value){
		if(!is_array($value)&&!empty($value)){
			$obj=self::_getObject('span');
			$obj->$key=$value;
			self::_save();
			$this->span=self::get('span');
		}	
	}	
	
	//For get().
	private function _toArray($obj,$indexed=false){
		$arr=Array();
		if(!empty($obj)&&is_object($obj)){
		foreach($obj->children() as $item){
			$str=preg_replace('/\r\n|\t/','',(string)$item);
			if($indexed)
				$arr[$item->getName()]=$str;
			else
				$arr[]=$str;
		}}
        return $arr;
	}
	
    //array get(string $key)
    public function get($key){
        if(is_string($key)&&!empty($key)){
			eval("\$obj=\$this->_xml->$key;");
			if($key=='span')
				return self::_toArray($obj,true);
			else
				return self::_toArray($obj);
        }else
            return false;
    }
	
	//Return the Value of $key->$index, $index begins with 1.
	public function getValue($key,$index=1){
		$v=$this->$key;
		return (string)$v[$index-1];		
	}
}
?>